#include	"common.h"
#include	"syscall.h"
#include	"isr.h"

#include	"monitor.h"

static void syscall_handler(struct registers regs);

static void *syscalls[4] = {
	monitor_write,
	monitor_write_hex,
	monitor_write_dec,
	fork
};
u32int num_syscalls = 4;

DEFN_SYSCALL0(fork, 3);

DEFN_SYSCALL1(monitor_write, 0, const char *);
DEFN_SYSCALL1(monitor_write_hex, 1, const char *);
DEFN_SYSCALL1(monitor_write_dec, 2, const char *);

void init_syscalls(){
	reg_intrh(0x80, syscall_handler);
}


void syscall_handler(struct registers regs){

	void *location;
	int ret;
/*
	monitor_write("System call #");
	monitor_write_hex(regs.eax);
	monitor_write("\n");
*/
	if(regs.eax >= num_syscalls){

		monitor_write("Illegal syscall #");
		monitor_write_dec(regs.eax);
		monitor_write("\n");

		return;
	}

	location = syscalls[regs.eax];
	asm volatile("	\
		push	%1;	\
		push	%2;	\
		push	%3;	\
		push	%4;	\
		push	%5;	\
		call	*%6;	\
		pop	%%ebx;	\
		pop	%%ebx;	\
		pop	%%ebx;	\
		pop	%%ebx;	\
		pop	%%ebx;	\
		" : "=a"(ret) : "r"(regs.edi), "r"(regs.esi), "r"(regs.edx), "r"(regs.ecx), "r"(regs.ebx), "r"(location));
	regs.eax = ret;
}
